package me.gavin.util

import android.widget.TextView
import androidx.databinding.BindingAdapter
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit


@BindingAdapter("bindTimeAbsolute")
fun TextView.bindTimeAbsoluteExt(time: Long) {
    text = time.timeAbsoluteExt
}

@BindingAdapter("bindTimeRelative")
fun TextView.bindTimeRelativeExt(time: Long) {
    text = time.timeRelativeExt
}

@BindingAdapter("bindTime", "bindTimeFormat", requireAll = false)
fun TextView.bindTimeRelativeExt(time: Long, format: String?) {
    text = SimpleDateFormat(format ?: "yyyy/MM/dd HH:mm", Locale.getDefault()).format(time)
}

val Long.timeAbsoluteExt: String
    get() {
        val cal = Calendar.getInstance().also { it.timeInMillis = this }
        val now = Calendar.getInstance()
        return when {
            cal.get(Calendar.YEAR) == now.get(Calendar.YEAR)
                    && cal.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR) -> {
                SimpleDateFormat("HH:mm", Locale.getDefault()).format(this)
            }
            cal.get(Calendar.YEAR) == now.get(Calendar.YEAR) -> {
                SimpleDateFormat("MM/dd HH:mm", Locale.getDefault()).format(this)
            }
            else -> {
                SimpleDateFormat("yyyy/MM/dd HH:mm", Locale.getDefault()).format(this)
            }
        }
    }

val Long.timeRelativeExt: String
    get() {
        val target = Calendar.getInstance().also { it.timeInMillis = this }
        val now = Calendar.getInstance()

        // 小于1分钟 - 刚刚
        if (now.timeInMillis - this < TimeUnit.MINUTES.toMillis(1)) return "刚刚"
        // 小于1小时 - x分钟前
        if (now.timeInMillis - this < TimeUnit.HOURS.toMillis(1))
            return "${(now.timeInMillis - this) / TimeUnit.MINUTES.toMillis(1)} 分钟前"
        // 小于1天 - x小时前
        if (now.timeInMillis - this < TimeUnit.DAYS.toMillis(1))
            return "${(now.timeInMillis - this) / TimeUnit.HOURS.toMillis(1)} 小时前"

        val dayStr = "${(now.timeInMillis - this) / TimeUnit.DAYS.toMillis(1)} 天前"

        val dd = now.get(Calendar.DAY_OF_MONTH) - target.get(Calendar.DAY_OF_MONTH)
        var dm = now.get(Calendar.MONTH) - target.get(Calendar.MONTH)
        var dy = now.get(Calendar.YEAR) - target.get(Calendar.YEAR)
        if (dd < 0) dm--
        if (dm < 0) {
            dm = (dm + 12) % 12
            dy--
        }

        // 大于12个月 - x年前
        if (dy > 0) return "$dy 年前"
        // 大于1个月 - x个月前 否则 - x天前
        return if (dm > 0) "$dm 个月前" else dayStr
    }